// pages/navigation/navigation.js
var httpUtil = require('../../../utils/httpUtil.js');
var uiUtil = require('../../../utils/uiUtil.js');
var util = require('../../../utils/util.js');
var WXBizDataCrypt = require('../../../utils/cryptoUtil.js');
const appId = 'wx2e65f1eb244a839b';
const app = getApp();
var that;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,//用户信息
    userLocation:null,//用户地理位置
    userLocationText:"地理位置加载中",
    userLocationStatus:0,
    pages:true,
    category: { //外卖品类
      type: false,
      categoryLists:null,
      categoryName:"全部品类",
      categoryIndex:-1
    },

    refresher:{ //下拉刷新
      home:false,
      order:false,
      my:false
    },

    mchLists: { //外卖商家列表
      totalCount: null,
      pageCount:null,
      pageNo:"0",
      pageSize:"30",
      dataList: []
    },
    mchRequestStatus:{ //外卖商家请求状态
      requestGoodsTask: null,
      isLoadingMore: false,
      enableLoadMore: true,
    },


    orderLists: { //订单列表
      page: {
        currentPage: "0",
        pageSize: "30",
        total: null
      },
      dataList: []
    },
    orderRequestStatus: { //订单列表请求状态
      requestGoodsTask: null,
      isLoadingMore: false,
      enableLoadMore: true,
    },


    icon:{
      pageThat:"home",
      home:"/resources/image/home.png",
      homeThat:"/resources/image/home-that.png",
      order:"/resources/image/order.png",
      orderThat:"/resources/image/order-that.png",
      my:"/resources/image/my.png",
      myThat:"/resources/image/my-that.png"
    },


    // 商家首页数据
    mchHome:null, //商家信息
    shopCartView:false, //展开购物车
    shopCartLists:[],//购物车列表
    chargeStrategy:[], //商家充值规则
    thatIndex: -1, // 充值规则选择下标

    pageThat:"page1", //子页面。page1:点菜；page2:商家;page3:会员;
    categoryId: null, //选择菜单

    scrollChildrens:[],
    cardDetail: null, //会员卡详情
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that=this;
    that.setData({
      options:options
    })
    if (app.globalData.userLocationStatus == 0) { //用户地理位置获取中
      that.setData({
        userLocationText:"地理位置获取中",
        userLocationStatus:0
      })
      app.locationRequestReadyCallback = res => {
        that.login(options)
      }
    } else if(app.globalData.userLocationStatus == 1){
      that.setData({
        userLocationText:"未获取到地理位置",
        userLocationStatus:1
      })
      that.login(options)
    }  else if(app.globalData.userLocationStatus == 3){
      that.setData({
        userLocationText:"未授权地理位置",
        userLocationStatus:3
      })
      that.login(options)
    } else {
      that.login(options)
    }
    
  },

  onShow:function(){
    let pageThat=that.data.icon.pageThat;
    if (pageThat =="home"){
      wx.setNavigationBarTitle({
        title: "首页"
      });
      wx.setNavigationBarColor({//设置导航栏颜色
        frontColor: "#000000",
        backgroundColor: "#ffffff"
      });
    } else if (pageThat == "order"){
      wx.setNavigationBarTitle({
        title: "订单"
      });
      wx.setNavigationBarColor({//设置导航栏颜色
        frontColor: "#000000",
        backgroundColor: "#ffffff"
      });
    } else if (pageThat == "my") {
      wx.setNavigationBarTitle({
        title: "我的"
      });
      wx.setNavigationBarColor({//设置导航栏颜色
        frontColor: "#ffffff",
        backgroundColor: "#2B2B37"
      });
    }
    that.handleGetUserInfo();
  },


  /**
   * 授权设置
   */
  openSetting(){
    wx.openSetting({
      success: (res) => {
        if (res.authSetting["scope.userLocation"]) {////如果用户重新同意了授权登录
          app.globalData.userLocationStatus=0;
          app.getLocation();
          if (app.globalData.userLocationStatus == 0) { //用户地理位置获取中
            that.setData({
              userLocationText:"地理位置获取中",
              userLocationStatus:0
            })
            app.locationRequestReadyCallback = res => {
              that.login(that.data.options)
            }
          } else if(app.globalData.userLocationStatus == 1){
            that.setData({
              userLocationText:"未获取到地理位置",
              userLocationStatus:1
            })
            that.login(that.data.options)
          } else {
            that.login(that.data.options)
          }
        }
      }
    })
  },

  /**
   * 初始加载页面
   */
  login(options){
    that.setData({
      userLocation: app.globalData.userLocation,
      pages: app.globalData.pages,
      "icon.pageThat":options.iconPageThat||"home"
    });
    that.handleGetUserInfo();

    if (app.globalData.pages){
      that.searchCategory();
      that.requestMyOrderList();
      that.getMchLists();
    } else {
      options.mchid = app.globalData.mchId;
      if (options.page) {
        that.setData({
          pageThat: options.page
        })
      }
      that.setData({
        pages: app.globalData.pages,
        authorizeFlag:app.globalData.authorizeFlag
      });

      that.searchMchHome(mchId);
      that.getShopCart(mchId);
      that.memActivitys(mchId);
    }
  },



  /**
   * 外卖品类查询
   */
  searchCategory(){
    httpUtil.PostRequest("searchCategory", {
    }, {
      success(res) {
        let category=[{
          categoryId:"all",
          categoryName:"全部品类"
        }]
        res = category.concat(res);
        that.setData({
          "category.categoryLists": res,
          "category.categoryIndex": 0,
          "category.categoryName": res[0].categoryName
        })
      },
      fail(code, res) {

      },
      complete() { }
    })
  },
  typeChange(){ //下拉框展开
    that.setData({
      "category.type": !that.data.category.type
    })
  },
  categoryChange(e){ //品类更改
    let index = e.currentTarget.dataset.index;
    that.setData({
      "category.type": !that.data.category.type,
      "category.categoryIndex": index,
      "category.categoryName": that.data.category.categoryLists[index].categoryName
    })
    that.getMchLists("", that.data.category.categoryLists[index].categoryId);
  },

  /**
   * 刷新外卖首页
   */
  refresherrefreshHome:function(){
    that.setData({
      mchLists: { //外卖商家列表
        totalCount: null,
        pageCount: null,
        pageNo: "0",
        pageSize: "30",
        dataList: []
      },
      mchRequestStatus: { //外卖商家请求状态
        requestGoodsTask: null,
        isLoadingMore: false,
        enableLoadMore: true,
      }
    })
    that.searchCategory();
    that.getMchLists();
  },

  /**
   * 获取外卖商家列表
   */
  getMchLists: function (e,categoryId) {
    let pageNo = parseInt(that.data.mchLists.pageNo)+1;
    let pageSize = that.data.mchLists.pageSize;
    let dataList = that.data.mchLists.dataList;
    let totalCount = that.data.mchLists.totalCount;
    let lat = that.data.userLocation.pois[0].location.lat;
    let lng = that.data.userLocation.pois[0].location.lng;

    var lastRequestTask = that.data.mchRequestStatus.requestGoodsTask;
    if (lastRequestTask) {
      try {
        lastRequestTask.abort()
      } catch (e) { }
    }

    if (categoryId) { //判断品类是否更改
      pageNo = 1;
      dataList = [];
      that.setData({
        "mchRequestStatus.enableLoadMore": true
      })
      if(categoryId=='all'){
        categoryId="";
      }
    }

    var curPage = that.data.mchLists.pageNo;
    if (curPage != 0 && (!that.data.mchRequestStatus.enableLoadMore || that.data.mchRequestStatus.isLoadingMore)) { //不可加载||正在加载\
      return;
    }

    var requestTask = httpUtil.PostRequest("taskOut", {
      lat: lat,
      lng: lng,
      categoryId: categoryId||"",
      pageNo: pageNo,
      pageSize: pageSize
    }, {
        success(res) {
          if (0 == that.data.mchLists.pageNo) {
            res.dataList = res.dataList || []
          } else {
            res.dataList = dataList.concat(res.dataList || []);
          }
          that.setData({
            mchLists: res,
            "mchRequestStatus.enableLoadMore": res.dataList.length < res.totalCount,
            "mchRequestStatus.fail": false
          })
          setTimeout(function(){
            that.setData({
              "refresher.home":false
            })
          },1500);
        },
        fail(code, res) {
          that.setData({
            "mchRequestStatus.enableLoadMore": false,
          })
          if (0 == that.data.mchLists.pageNo) { //内容为空
            that.setData({
              "mchRequestStatus.fail":true
            })
          } else {
            uiUtil.showToast(res);
          }
        },
        complete() {
          that.setData({
            "mchRequestStatus.isLoadingMore": false
          })
        }
      })
    that.setData({
      "mchRequestStatus.requestGoodsTask": requestTask
    })
  },



  /**
   * 获取用户信息结果处理
   */
  handleGetUserInfo() {
    httpUtil.PostRequest("userinfo", {
      pageNo: "1",
      pageSize: "1"
    }, {
      success(res) {
        that.setData({
          userInfo: res
        })
        setTimeout(function(){
          that.setData({
            "refresher.my": false
          })
        },1500);
        // if (res.ifFinishedInfo==0){
        //   that.noUserInfo();
        // }
      },
      fail(code, res) {
        uiUtil.showToast(res);
      },
      complete() { }
    })
  },
  noUserInfo(res) { //未完善用户信息，跳转会员信息页面
    wx.navigateTo({
      url: '/pages/user/information/information'
    })
  },


  /**
  * 回调
  */
  onResultRegisterSuccess(e) {
    this.handleGetUserInfo()
  },

  

  /**
  * 跳转会员卡详情页面
  */
  goShopDetails(e) {
    let item = e.currentTarget.dataset.item;
    if (item){
      wx.navigateTo({
        // url: '/pages/shop/shop/shop?id=' + item.id + "&page=page3&mchId=" + item.mchId
        url: '/pages/ticket/ticket-details/ticket-details?id=' + item.id + "&page=page3&mchId=" + item.mchId
      })
    }
  },

  /**
   * 导航
   */
  navigationChange:function(res){
    let page = res.currentTarget.dataset.page;
    let title = res.currentTarget.dataset.title;
    let frontColor = res.currentTarget.dataset.frontcolor;
    let backgroundColor = res.currentTarget.dataset.backgroundcolor;
    
    wx.setNavigationBarTitle({
      title: title
    });
    wx.setNavigationBarColor({//设置导航栏颜色
      frontColor: frontColor,
      backgroundColor: backgroundColor
    });
    that.setData({
      "icon.pageThat":page
    });
    
  },

  /**
   * 订单下拉刷新
   */
  refresherrefreshOrder: function () {
    that.setData({
      orderLists: { 
        page: {
          currentPage: "0",
          pageSize: "30",
          total: null
        },
        dataList: []
      },
      orderRequestStatus: { 
        requestGoodsTask: null,
        isLoadingMore: false,
        enableLoadMore: true,
      }
    })
    that.requestMyOrderList();
  },

  /**
   * 获取订单列表
   */
  requestMyOrderList() {
    let currentPage = parseInt(that.data.orderLists.page.currentPage)+1;
    let pageSize = that.data.orderLists.page.pageSize;
    let dataList = that.data.orderLists.dataList;

    var lastRequestTask = that.data.orderRequestStatus.requestGoodsTask;
    if (lastRequestTask) {
      try {
        lastRequestTask.abort()
      } catch (e) { }
    }

    var curPage = that.data.orderLists.page.currentPage;
    if (curPage != 0 && (!that.data.orderRequestStatus.enableLoadMore || that.data.orderRequestStatus.isLoadingMore)) { //不可加载||正在加载\
      return;
    }

    var requestTask = httpUtil.PostRequest("searchUserOrder", {
      currentPage: currentPage,
      pageSize: pageSize
    }, {
      success(res) {
        if (0 == that.data.orderLists.page.currentPage) {
          res.dataList = res.dataList || []
        } else {
          res.dataList = dataList.concat(res.dataList || []);
        }
        that.setData({
          orderLists: res,
          "orderRequestStatus.enableLoadMore": res.dataList.length < res.page.total,
          "orderRequestStatus.fail": false
        })
        setTimeout(function(){
          that.setData({
            "refresher.order": false
          })
        },1500);
      },
      fail(code, res) {
        that.setData({
          "orderRequestStatus.enableLoadMore": false,
        })
        if (0 == that.data.orderLists.page.currentPage) { //内容为空
          that.setData({
            "orderRequestStatus.fail": true
          })
        } else {
          uiUtil.showToast(res);
        }
      },
      complete() {
        that.setData({
          "orderRequestStatus.isLoadingMore": false
        })
      }
    })
    that.setData({
      "orderRequestStatus.requestGoodsTask": requestTask
    })
  },

  /**
   * 取消订单
   */
  delOrder(e){
    let orderNo = e.currentTarget.dataset.orderno;
    let index = e.currentTarget.dataset.index;
    let orderStatus="orderLists.dataList["+index+"].orderStatus";
    httpUtil.PostRequest("delOrder", {
      orderNo: orderNo
    }, {
        success(res) {
          uiUtil.showToast("取消成功");
          // 更改订单状态
          that.setData({
            [orderStatus]:"8"
          })
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
   * 确认送达
   */
  orderStatusChange(e){
    let orderNo = e.currentTarget.dataset.orderno;
    let index = e.currentTarget.dataset.index;
    let status = e.currentTarget.dataset.status;
    let orderStatus="orderLists.dataList["+index+"].orderStatus";
    httpUtil.PostRequest("updateUserOrderStatus", {
      orderNo: orderNo,
	    status:status
    }, {
        success(res) {
          uiUtil.showToast("确认成功");
          // 更改订单状态
          that.setData({
            [orderStatus]:status
          })
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
   * 再来一单
   */
  anotherList(e){
    let mchId = e.currentTarget.dataset.greens.mchId;
    let orderGreens = JSON.stringify(e.currentTarget.dataset.greens);
    httpUtil.PostRequest("searchMchHome", {
      mchId: mchId
    }, {
      success(res) {
        if(!res){
          uiUtil.showToast("该商户已下架");
        } else if (res.operatingStatus!=1){
          uiUtil.showToast("该商户已打烊");
        } else {
          wx.navigateTo({
            url: '/pages/shop/shop/shop?mchId='+mchId+'&orderGreens=' + orderGreens,
          })
        }
      },
      fail(code, res) {
        uiUtil.showToast(res);
      }
    })
  },















  /**
   * 
   * 
   * 商家首页接口
   * 
   * 
   */


  /**
   * 转发分享设置
   */
  onShareAppMessage: function (res) {
    return util.handleShareApp('shop', that.data.mchHome)
  },

  /**
   * 充值选择金额
   */
  bindThatChange: function (e) {
    let index = e.currentTarget.dataset.index;
    that.setData({
      thatIndex: index
    })
  },

  /**
   * 提示选择充值金额
   */
  hintCharge:function(e){
    uiUtil.showToast("请选择充值金额");
  },

  /**
   * 跳转到余额明细页面
   */
  balanceDetail(e) {
    if(that.data.cardDetail){
      let id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/ticket/ticket-money/ticket-money?id=' + id
      })
    } else {
      uiUtil.showToast("还未成为会员，无交易明细");
    }
  },

  /**
   * 获取会员卡详细信息
   */
  ticketDetails() {
    let mCardId= that.data.mchHome.memCardId;
    httpUtil.PostRequest("detail", {
      mCardId: mCardId
    }, {
        success(res) {
          that.setData({
            cardDetail: res
          })
        },
        fail(code, res) {
          // uiUtil.showToast(res);
        },
        complete() { }
      })
  },


  /**
   * 获取商户充值规则
   */
  memActivitys(mchId){
    httpUtil.PostRequest("memActivitys", {
      mchId: mchId
    }, {
        success(res) {
          that.setData({
            chargeStrategy: res
          })
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
   * 商家首页查询
   */
  searchMchHome(mchId) {
    httpUtil.PostRequest("searchMchHome", {
      mchId: mchId
    }, {
      success(res) {
        wx.setNavigationBarTitle({
          title: res.mchName
        });
        that.setData({
          mchHome:res,
          categoryId:res.products[0].categoryId
        });
        that.ticketDetails();
        that.scrollChildrenHeight();
      },
      fail(code, res) {
        uiUtil.showToast(res);
      },
      complete() { }
    })
  },

  /**
   * 展开购物车
   */
  shopCartViewChange() {
    if (that.data.shopCartLists.length>0){
      that.setData({
        shopCartView: !that.data.shopCartView
      })
    } 
  },

  /**
   * 购物车查询
   */
  getShopCart(mchId){
    httpUtil.PostRequest("searchCart", {
      mchId: mchId
    }, {
        success(res) {
          if(res.length==0){
            that.setData({
              shopCartView: false
            })
          }
          that.setData({
            shopCartLists:res
          })
          uiUtil.hideLoading();
        },
        fail(code, res) {
          uiUtil.showToast(res)
        },
        complete() { }
      })
  },

  /**
   * 购物车保存
   */
  getSaveCart(e) {
    let item = e.currentTarget.dataset.item;
    let mchId = that.data.mchHome.mchId;
    let mchName = that.data.mchHome.mchName; 
    let productcount = e.currentTarget.dataset.productcount;
    let type = e.currentTarget.dataset.type;
    productcount = parseInt(productcount) + parseInt(type);

    httpUtil.PostRequest("saveCart", {
      mchId: mchId,
      mchName: mchName,
      productId: item.productId||item.id,
      productName: item.name || item.productName,
      productImgUrl: item.imageUrl || item.productImgUrl,
      productCount: productcount,
      price: item.price,
      amount: item.price * productcount
    }, {
        success(res) {
          that.getShopCart(mchId);
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  }, 

  /**
   * 购物车删除
   */
  getDelCart(e) {
    let productId =e.id|| e.currentTarget.dataset.productid;
    let cartId = that.data.shopCartLists[0].id;
    let mchId = that.data.mchHome.mchId;

    httpUtil.PostRequest("delCart", {
      cartId: cartId,
      productId: productId
    }, {
      success(res) {
        that.getShopCart(mchId);
      },
      fail(code, res) {
        uiUtil.showToast(res);
      },
      complete() { }
    })
  }, 

  /**
   * 收藏商家
   */
  collectChange:function(){
    let mchHome = that.data.mchHome;
    httpUtil.PostRequest("saveCollect", {
      mchId: mchHome.mchId,
      mchName: mchHome.mchName,
      mchAddress: mchHome.mchAddress,
      mchPrice: mchHome.distributionPrice,
      mchType: mchHome.mchType,
      mchLogoUrl: mchHome.mchLogoUrl
    }, {
        success(res) {
          that.setData({
            "mchHome.isCollect":res
          })
        },
        fail(code, res) {
          uiUtil.showToast(res);
        },
        complete() { }
      })
  },

  /**
   * 拨打商家电话
   */
  mchPhone:function(e){
    let phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },

  /**
   * 取消收藏
   */
  delCollectChange:function(){
    let id=that.data.mchHome.isCollect;
    httpUtil.PostRequest("delCollect", {
      id:id
    }, {
        success(res) {
          that.setData({
            "mchHome.isCollect": "0"
          })

          var pages = getCurrentPages();
          var lastPage = pages[pages.length - 2];
          if (lastPage.route == "pages/shop/shop-collect/shop-collect") {
            lastPage.onResultRegisterSuccess();
          }
        },
        fail(code, res) {
          uiUtil.showToast(res);
        }
      })
  },


  /**
   * 点击去结算，获取用户信息
   */
  getuserinfo(e){
    if(e.detail.errMsg=="getUserInfo:fail auth deny"){ //用户拒绝授权获取用户信息
      return
    }
    
    let mchhome=e.currentTarget.dataset.mchhome;
    let shopcartlists=e.currentTarget.dataset.shopcartlists;

    var sessionKey = app.globalData.sessionKey;
    var encryptedData = e.detail.encryptedData;
    var iv =  e.detail.iv;
    var pc = new WXBizDataCrypt(appId, sessionKey)
    var data = pc.decryptData(encryptedData , iv)
    app.globalData.userInfo=data;

    wx.navigateTo({
      url:"/pages/index/order/order-pre/order-pre?mchHome="+mchhome+"&shopCartLists="+shopcartlists
    })
  },
  getuserinfoPageChange(e){
    if(e.detail.errMsg=="getUserInfo:fail auth deny"){ //用户拒绝授权获取用户信息
      return
    }

    var sessionKey = app.globalData.sessionKey;
    var encryptedData = e.detail.encryptedData;
    var iv =  e.detail.iv;
    var pc = new WXBizDataCrypt(appId, sessionKey)
    var data = pc.decryptData(encryptedData , iv)
    app.globalData.userInfo=data;

    that.pageChange(e);
  },


  /**
   * 点击立即充值，获取用户手机号
   */
  getphonenumber (e) {
    if(e.detail.errMsg=="getUserInfo:fail auth deny"){ //用户拒绝授权获取用户手机号
      return
    }

    var sessionKey = app.globalData.sessionKey;
    var encryptedData = e.detail.encryptedData;
    var iv =  e.detail.iv;

    var pc = new WXBizDataCrypt(appId, sessionKey);
    var data = pc.decryptData(encryptedData , iv);
    app.globalData.userPhone=data;

    let mchkey=e.currentTarget.dataset.mchkey;
    let currentPrice=that.data.chargeStrategy[that.data.thatIndex].topUp;
    let activeType=that.data.chargeStrategy[that.data.thatIndex].id;
    that.getUser(mchkey,currentPrice,activeType);
  },


  /**
   * 提交用户信息
   */
  getUser: function (mchkey,currentPrice,activeType){
    let userPhone=app.globalData.userPhone;
    let userInfo=app.globalData.userInfo;
    httpUtil.PostRequest("update_small_user", {
      wechantName: userInfo.nickName,
      phone: userPhone.purePhoneNumber,
      avatarUrl: userInfo.avatarUrl,
      unionId: userInfo.unionId
    }, {
      success(res) {
        app.globalData.authorizeFlag=true;
        that.setData({
          authorizeFlag:true
        })
        wx.navigateTo({
          url:"/pages/pay/pay?mchkey="+mchkey+"&payType=CHARGE&currentPrice="+currentPrice+"&activeType="+activeType
        })
      },
      fail(code, res) {
        uiUtil.showToast(res);
      }
    })
  },


  /**
   * 页面点击操作
   */
  pageChange: function (res) {
    let page = res.currentTarget.dataset.page;
    that.setData({
      pageThat: page
    });

  },
  categoryIdChange: function (res) {
    let categoryId = res.currentTarget.dataset.categoryid;
    that.setData({
      categoryIdIndex: null,
      categoryId: categoryId
    });

  },
  scrollChildrenHeight(){
    let products = that.data.mchHome.products;
    var scrollChildrens=[];
    for (var index = 0; index < products.length;index++){
      let query = wx.createSelectorQuery();
      query.select('#category' + products[index].categoryId).boundingClientRect();
      query.selectViewport().scrollOffset();
      query.exec(function (res) {
        scrollChildrens.push(res[0]);
      })
    }
    that.setData({
      scrollChildrens: scrollChildrens
    })
  },
  scrollHeight:function(e){
    // let y = e.detail.scrollTop;
    // let scrollChildrens = that.data.scrollChildrens;
    
    // console.log(y, scrollChildrens);
    // for (let index = 0; index < scrollChildrens.length;index++){
    //   let top = scrollChildrens[index].top;
    //   let nextTop = scrollChildrens[index+1].top;
    //   console.log(top, nextTop);
    //   if (y >= top && (y < nextTop || nextTop==0)){
    //     console.log(index)
    //     that.setData({
    //       categoryId:null,
    //       categoryIdIndex: index
    //     })
    //     return ;
    //   }
    // }
  }
})